package com.lire.shop.controller;

import com.google.gson.Gson;
import com.lire.shop.dao.ProductRepository;
import com.lire.shop.entity.Product;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Mac;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "商品管理")
@RestController
public class ProductController {

    @Autowired
    private Gson gson;

    @Autowired
    private ProductRepository productRepository;

    @Operation(summary = "查看所有商品", tags = {"商品管理", "01-test"})
    @ApiResponses({
            @ApiResponse(responseCode = "200"
                    , content = {@Content(schema = @Schema(implementation = Product.class), mediaType = "application/json")})
    })
    @GetMapping("/product/list")
    public String listProduct() {
        List<Product> products = productRepository.findAll();

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("products", products);
        map.put("productsCount", products.size());
        return gson.toJson(map);
    }

    @PostMapping("/product")
    public String addProduct(Product product) {
        Product save = productRepository.save(product);
        return new Gson().toJson(save);
    }

    @PutMapping("/product")
    public String updateProduct(Product product) {
        Product newProduct = productRepository.save(product);
        return new Gson().toJson(newProduct);
    }

    @DeleteMapping("/product/{pid}")
    public String deleteProduct(@PathVariable Long pid) {
        productRepository.deleteById(pid);
        return "A product is deleted!";
    }
}
